package com.moonciki.artadmin.core.utils;

import com.alibaba.fastjson.JSON;
import com.moonciki.artadmin.core.enums.ResponseEnum;
import com.moonciki.artadmin.core.exception.CustomException;
import lombok.Data;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 对象转换工具
 * @param <T>
 * @param <K>
 */
@Data
public class ConvertUtil<T, K> {

    private K copy(K target){

        String jsonData = JSON.toJSONString(target);

        K newObj = (K) JSON.parseObject(jsonData, target.getClass());

        return newObj;
    }

    /**
     * 将对象转换，被转换对象必须实现 convert 方法
     * @param sourceList
     * @param target
     * @return
     */
    public List<K> beanConvertList(List<T> sourceList, K target) {
        List<K> resultList = null;

        if (sourceList != null) {
            resultList = new ArrayList<>();

            for (T oneOrigin : sourceList) {

                K newObj = copy(target);

                K result = beanConvertObject(oneOrigin, newObj);

                resultList.add(result);
            }
        }

        return resultList;
    }

    public K beanConvertObject(T source, K target) {
        K result = null;

        if(target == null){
            throw CustomException.createException(ResponseEnum.sys_error.info());
        }

        if (source != null) {
            result = target;

            BeanUtils.copyProperties(source, result, target.getClass());
        }
        return result;
    }

    /**
     * 转换list
     * @param sourceList
     * @param target
     * @param <T>
     * @param <K>
     * @return
     */
    public static <T, K> List<K> beanConvert(List<T> sourceList, K target) {
        ConvertUtil<T, K> convertUtil = new ConvertUtil<>();

        List<K> result = convertUtil.beanConvertList(sourceList, target);

        return result;
    }

    /**
     * 转换object
     * @param source
     * @param target
     * @param <T>
     * @param <K>
     * @return
     */
    public static <T, K> K beanConvert(T source, K target) {
        ConvertUtil<T, K> convertUtil = new ConvertUtil<>();

        K result = convertUtil.beanConvertObject(source, target);

        return result;
    }

}